<template>
  <view class="container">
    <view class="list" v-if="list.length > 0">
      <u-swipe-action :show="item.show" :index="index" v-for="(item, index) in list" :key="index" @click="click" :options="options" @open="open">
        <view class="item u-border-bottom">
          <!-- 此层wrap在此为必写的，否则可能会出现标题定位错误 -->
          <view class="title-wrap">
            <text class="title u-line-2">{{ item.create_time }}：{{ item.content }}</text>
          </view>
        </view>
      </u-swipe-action>
      <u-loadmore :status="status" bg-color="#f8f8f8" margin-top="50" margin-bottom="50" @loadmore="loadMore" :loadText="loadText" />
    </view>
    <view class="empty-box" v-else><u-empty text="还未发表过评论~~" mode="message" /></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      page: 1,
      list: [],
      status: 'loading',
      options: [{ text: '删除', style: { backgroundColor: '#dd524d' } }],
      loadText: {
        loadmore: '点击或轻轻上拉',
        loading: '努力加载中',
        nomore: '实在没有了'
      }
    };
  },
  onLoad(options) {
    this.getList();
  },
  onReachBottom() {
    this.loadMore();
  },
  methods: {
    getList() {
      this.status = 'loading';
      this.$api.get({
        url: 'user/comments/my',
        data: {
          page: `${this.page},20` // 一页显示20条
        },
        success: res => {
          if (res.code == 1) {
            let list = res.data.list.map(item => {
              return {
                id: item.id,
                content: item.content,
                show: false,
                create_time: item.create_time
              };
            });
            this.list = this.list.concat(list);
            // 分页判断
            if (list.length < 20) {
              this.status = 'nomore';
            } else {
              this.status = 'loadmore';
              this.page++;
            }
          }
        }
      });
    },
    loadMore() {
      if (this.status === 'loadmore') {
        this.getList();
      }
    },
    click(index, type) {
      if (type == 0) {
        this.$api.post({
          url: `user/comments/delComments`,
          data: {
            id: this.list[index].id
          },
          success: res => {
            this.$toast(res.msg);
            if (res.code == 1) {
              this.list.splice(index, 1);
            }
          }
        });
      }
    },
    // 如果打开一个的时候，不需要关闭其他，则无需实现本方法
    open(index) {
      // 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
      // 原本为'false'，再次设置为'false'会无效
      this.list[index].show = true;
      this.list.map((val, idx) => {
        if (index != idx) this.list[idx].show = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.list {
  .item {
    display: flex;
    padding: 20rpx;
  }

  .title {
    text-align: left;
    font-size: 28rpx;
    color: $u-content-color;
    margin-top: 20rpx;
  }
}
</style>
